package com.liuqi.voicenotes.data

import android.content.Context
import com.liuqi.voicenotes.data.db.AppDatabase
import com.liuqi.voicenotes.data.db.TaskEntity
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

class TaskRepository(private val context: Context) {
    private val dao = AppDatabase.get(context).taskDao()

    val tasks: Flow<List<Task>> = dao.observeAll().map { list ->
        list.map { it.toDomain() }
    }

    suspend fun add(task: Task): Long = dao.insert(task.toEntity())

    suspend fun update(task: Task) = dao.update(task.toEntity())

    suspend fun delete(task: Task) = dao.delete(task.toEntity())

    suspend fun setCompleted(id: Long, completed: Boolean) = dao.setCompleted(id, completed)

    private fun TaskEntity.toDomain() = Task(id, title, dueAtMillis, priority, completed)
    private fun Task.toEntity() = TaskEntity(id = if (id == 0L) 0 else id, title = title, dueAtMillis = dueAtMillis, priority = priority, completed = completed)
}